package com.pandas.community.controller;

import com.alibaba.fastjson.JSONObject;
import com.pandas.community.Utils.CommunityConstant;
import com.pandas.community.Utils.CommunityUtil;
import com.pandas.community.Utils.HostHolder;
import com.pandas.community.entity.Message;
import com.pandas.community.entity.Page;
import com.pandas.community.entity.User;
import com.pandas.community.service.MessageService;
import com.pandas.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

@Controller
public class MessageController implements CommunityConstant {

    @Autowired
    private MessageService messageService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    //会话列表
    @RequestMapping(value="/letter/list", method = RequestMethod.GET)
    public String getLetterList(Model model, Page page){
        User user = hostHolder.getUser();

        //设置分页信息
        page.setPageCapacity(5);
        page.setPath("/letter/list");
        page.setInfoAmount(messageService.selectConversationsCount(user.getId()));


        List<Message> conservationList = messageService.selectConversations(user.getId(),
                page.getOffset(), page.getPageCapacity());

        List<Map<String, Object>> conservations = new ArrayList<>();

        if(conservationList != null){
            for(Message message : conservationList){
                Map<String, Object> map = new HashMap<>();
                // 某条会话的最新消息
                map.put("conversation", message);
                // 某条会话的消息数
                map.put("lettersCount", messageService.selectLettersCount(message.getConversationId()));
                // 某条会话的未读消息书
                map.put("unreadCount", messageService.selectUnReadLettersCount(user.getId(), message.getConversationId()));
                // 某条会话的对象
                int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
                map.put("target", userService.selectById(targetId));

                conservations.add(map);
            }
        }

        model.addAttribute("conversations", conservations);
        // 总共的未读消息数
        model.addAttribute("totalUnreadMessageCount", messageService.selectUnReadLettersCount(user.getId(), null));

        int unreadNoticeCount = messageService.selectUnreadNoticeCount(user.getId(),null);
        model.addAttribute("totalUnreadNoticeCount", unreadNoticeCount);

        return "/site/letter";
    }

    //消息列表
    @RequestMapping(value = "/letter/detail/{conversationId}", method = RequestMethod.GET)
    public String getLetterDetail(@PathVariable("conversationId") String conversationId, Page page, Model model){
        //分页信息
        page.setPageCapacity(5);
        page.setPath("/letter/detail/" + conversationId);
        page.setInfoAmount(messageService.selectLettersCount(conversationId));

        //私信列表
        List<Message> letterList = messageService.selectLetters(conversationId, page.getOffset(), page.getPageCapacity());
        List<Map<String, Object>> letters = new ArrayList<>();
        if(letterList != null){
            for(Message message : letterList){
                Map<String, Object> map = new HashMap<>();
                map.put("letter", message);
                map.put("fromUser", userService.selectById(message.getFromId()));
                letters.add(map);
            }
        }
        model.addAttribute("letters", letters);
        model.addAttribute("target", getletter(conversationId));

        //设置已读
        List<Integer> ids = getLetterIds(letterList);
        if(!ids.isEmpty()){
            messageService.readMessage(ids);
        }
        return "/site/letter-detail";
    }

    // 需要标记为已读的消息id
    private List<Integer> getLetterIds(List<Message> letters){
        List<Integer> ids = new ArrayList<>();
        if(letters != null){
            for(Message message : letters){
                if(hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0){
                    ids.add(message.getId());
                }
            }
        }

        return ids;
    }


    private User getletter(String conversationId){
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);
        if(hostHolder.getUser().getId() == id0){
            return userService.selectById(id1);
        }else{
            return userService.selectById(id0);
        }
    }


    @RequestMapping(value = "/letter/send", method = RequestMethod.POST)
    @ResponseBody
    public String sendLetter(String toName, String content){
        User target = userService.selectByName(toName);
        if(target == null) return CommunityUtil.getJSONString(1, "目标用户不存在！");

        Message message = new Message();
        message.setFromId(hostHolder.getUser().getId());
        message.setToId(target.getId());
        message.setContent(content);
        if(message.getFromId() < message.getToId()){
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        }else{
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }

        message.setCreateTime(new Date());
        messageService.insertMessage(message);
        return CommunityUtil.getJSONString(0);
    }

    @RequestMapping(value="/notice/list",method = RequestMethod.GET)
    public String getNoticeList(Model model){
        User user = hostHolder.getUser();

        //查询评论类通知
        Message message = messageService.getLatestNotice(user.getId(), TOPIC_COMMENT);
        if(message != null){
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, Map.class);

            messageMap.put("user", userService.selectById((Integer)data.get("userId")));
            messageMap.put("entityType", data.get("entityType"));
            messageMap.put("entityId", data.get("entityId"));
            messageMap.put("postId",data.get("postId"));

            int messageCount = messageService.selectNoticeCount(user.getId(),TOPIC_COMMENT);
            messageMap.put("messageCount", messageCount);

            int unredMessageCount = messageService.selectUnreadNoticeCount(user.getId(), TOPIC_COMMENT);
            messageMap.put("unReadMessageCount", unredMessageCount);

            model.addAttribute("commentNotice", messageMap);
        }

        //查询点赞类通知
        message = messageService.getLatestNotice(user.getId(), TOPIC_LIKE);
        if(message != null){
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageMap.put("user", userService.selectById((Integer)data.get("userId")));
            messageMap.put("entityType", data.get("entityType"));
            messageMap.put("entityId", data.get("entityId"));
            messageMap.put("postId",data.get("postId"));

            int messageCount = messageService.selectNoticeCount(user.getId(),TOPIC_LIKE);
            messageMap.put("messageCount", messageCount);

            int unredMessageCount = messageService.selectUnreadNoticeCount(user.getId(), TOPIC_LIKE);
            messageMap.put("unReadMessageCount", unredMessageCount);

            model.addAttribute("likeNotice", messageMap);
        }

        //查询关注类通知
        message = messageService.getLatestNotice(user.getId(), TOPIC_FOLLOW);
        if(message != null){
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

            messageMap.put("user", userService.selectById((Integer)data.get("userId")));
            messageMap.put("entityType", data.get("entityType"));
            messageMap.put("entityId", data.get("entityId"));

            int messageCount = messageService.selectNoticeCount(user.getId(),TOPIC_FOLLOW);
            messageMap.put("messageCount", messageCount);

            int unredMessageCount = messageService.selectUnreadNoticeCount(user.getId(), TOPIC_FOLLOW);
            messageMap.put("unReadMessageCount", unredMessageCount);
            model.addAttribute("followNotice", messageMap);
        }


        int unreadLetterCount = messageService.selectUnReadLettersCount(user.getId(),null);
        model.addAttribute("totalUnreadMessageCount", unreadLetterCount);
        int unreadNoticeCount = messageService.selectUnreadNoticeCount(user.getId(),null);
        model.addAttribute("totalUnreadNoticeCount", unreadNoticeCount);


        return "/site/notice";

    }


    @RequestMapping(value="/notice/detail/{topic}",method = RequestMethod.GET)
    public String getNoticeDetail(@PathVariable("topic")String topic, Model model, Page page){
        User user = hostHolder.getUser();

        page.setPageCapacity(5);
        page.setPath("/notice/detail/" + topic);
        page.setInfoAmount(messageService.selectNoticeCount(user.getId(), topic));

        List<Message> noticeList = messageService.selectNotice(user.getId(), topic, page.getOffset(), page.getPageCapacity());

        List<Map<String,Object>> notices = new ArrayList<>();
        if(noticeList != null){
            for(Message message : noticeList){
                Map<String, Object> map = new HashMap<>();
                //通知
                map.put("notice",message);
                //内容
                String content = HtmlUtils.htmlUnescape(message.getContent());
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
                map.put("user", userService.selectById((Integer) data.get("userId")));
                map.put("entityType", data.get("entityType"));
                map.put("entityId", data.get("entityId"));
                map.put("postId", data.get("postId"));

                //通知的作者  这边都是System
                map.put("fromUser", userService.selectById(message.getFromId()));
                notices.add(map);
            }
        }
        model.addAttribute("notices", notices);
        //设置已读
        List<Integer> ids = getLetterIds(noticeList);

        if(!ids.isEmpty()) messageService.readMessage(ids);
        return "/site/notice-detail";
    }

}
